package com.fenghongzhang.day011;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;
import android.util.Log;

//创建一个内容观察者
public class MyOber extends ContentObserver {
    private static final String TAG = "MyOber";

    //上下文
    private Context context;
    //main页面传过来的handler
    private Handler handler;
    public MyOber(Handler handler,Context context) {
        super(handler);
        this.handler = handler;
        this.context = context;
    }

    //3 .一定数据库, 有变化,会自动调用这个方法.
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

//        Log.i(TAG, "onChange: ");

        //一定有变化,就是来信息了. 读取信息,发给页面就可以了

        ContentResolver contentResolver = context.getContentResolver();
        Cursor query = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
        if(query != null){
            //所有的短信
//            while(query.moveToNext()){
//
//            }
            //只读第一条
            if(query.moveToFirst()){
                String string = query.getString(query.getColumnIndex(Telephony.Sms.BODY));
                Log.i(TAG, "onChange: "+string);

                //用handler 发消息
                Message obtain = Message.obtain();
                obtain.obj = string;
                handler.sendMessage(obtain);

            }

            query.close();
        }


    }
}
